package com.cxl.demo.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;

import java.util.Calendar;
import java.util.Date;

public class JWTUtil {
    public String getToken(Integer userId){
        String Id=userId+"";
        Date now=new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(now);
        c.add(Calendar.MINUTE, +14400);
        Date after=c.getTime();

        String token = JWT.create().withAudience(Id)   //签发对象
                .withIssuedAt(now)    //发行时间
                .withExpiresAt(after)//有效时间
                .withClaim("userId", Id)
                .sign(Algorithm.HMAC256("TCHZCXLBYSJ"));   //加密
        return token;
    }
    public boolean TokenTime(String token){

        try{
            Date date1 = JWT.decode(token).getExpiresAt();
            return date1.after(new Date());
        }catch (Exception e){
            return false;
        }

    }
    public Integer getUserId(String token){
        String userId=null;
        if(TokenTime(token)){
            try {
               userId = JWT.decode(token).getAudience().get(0);
               return Integer.parseInt(userId);
            } catch (JWTDecodeException j) {
                return 0;
            }
        }else {
            return 0;
        }
    }
}
